package com.googlecode.saucelabs;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Goal which touches a timestamp file.
 * 
 * @goal list-tunnels
 */
public class ListTunnelsMojo extends AbstractSauceMojo {
	public void execute() throws MojoExecutionException, MojoFailureException {
		HttpClient httpClient = getHttpClient();
		HttpGet httpGet = getRequest(HttpGet.class, "/rest/%s/tunnels",
				username);

		try {
			HttpResponse response = httpClient.execute(httpGet);

			String responseString = EntityUtils.toString(response.getEntity());

			JSONArray jsonArray = new JSONArray(responseString);

			if (0 == jsonArray.length()) {
				logMessage("There are no tunnels set up");
			} else {
				logMessage("There are %d tunnels set up", jsonArray.length());

				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jsonObject = jsonArray.getJSONObject(i);

					for (int j = 0; j < jsonObject.length(); j++) {
						String jsonKey = "" + jsonObject.names().get(j);
						String jsonValue = jsonObject.getString(jsonKey);

						logMessage(" %d: %s: %s", i, jsonKey, jsonValue);
					}
				}
			}

		} catch (Exception e) {
			throw new MojoExecutionException("Failure", e);
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
	}
}
